# python3.7
# -*- coding: utf-8 -*-
# @Time     : 2023/2/25
# @Author   :
# @File     : qidianCode.py
# @function : 爬取起点中文网排行榜
# @Software : PyCharm Community Edition
# @Knowledge: requests、BeautifulSoup、写文件
from bs4 import BeautifulSoup
import requests
import xlwt


datas = []

# 将数据写入文件
def save_file(fileName):
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet("Sheet1")
    # 写表头
    sheet.write(0, 0, "小说名")
    sheet.write(0, 1, "类型")
    sheet.write(0, 2, "简介")
    sheet.write(0, 3, "更新情况")

    # 写数据
    for i, data in enumerate(datas, start=1):
        sheet.write(i, 0, data['title'])
        sheet.write(i, 1, data['type'])
        sheet.write(i, 2, data['intro'])
        sheet.write(i, 3, data['update_status'])

    workbook.save(fileName)
    print(f"数据已保存至 {fileName}")

# 获得数据存入datas列表
def gain_data(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, features='lxml')
    books = soup.find_all('div', class_='book-mid-info')

    # 遍历找到的div盒子，在里面便利对应的数据，并构建一个字典列表datas
    for book in books:
        title = book.find('h2').get_text(strip=True)
        type = book.find('p', class_='author').span.get_text(strip=True)  # Assuming type is within the 'author' paragraph
        intro = book.find('p', class_='intro').get_text(strip=True)
        update_status = book.find('p', class_='update').get_text(strip=True)  # Assuming update status is in a 'update' paragraph
        datas.append({'title': title, 'type': type, 'intro': intro, 'update_status': update_status})

# 在控制台输出数据
def show_data():
    for i, data in enumerate(datas, start=1):
        print(f"{i}. 小说名: {data['title']}")
        print(f"   类型: {data['type']}")
        print(f"   简介: {data['intro']}")
        print(f"   更新情况: {data['update_status']}")
        print()

# 主程序
if __name__ == "__main__":
    # 网址列表
    urllist = ['http://localhost:8080/qidian/yuepiao.html',
               'http://localhost:8080/qidian/hotsales.html',
               'http://localhost:8080/qidian/readindex.html',
               'http://localhost:8080/qidian/newfans.html',
               'http://localhost:8080/qidian/recom.html',
               'http://localhost:8080/qidian/collect.html',
               'http://localhost:8080/qidian/vipup.html',
               'http://localhost:8080/qidian/vipcollect.html']

    choicesList = ["1.月票榜", " 2.畅销榜", "3.阅读指数榜", "4.书友榜", "5.推荐榜", "6.收藏榜", "7.更新榜", "8.VIP收藏榜"]
    print(choicesList)
    choice = int(input('请选择你想查看的榜单:'))
    url = urllist[choice - 1]
    gain_data(url)
    show_data()
    save_file(choicesList[choice - 1] + ".xls")
